package com.hongning.railway.ui.main.fragments.college.exam;

import android.app.Application;
import android.content.Context;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import com.hongning.railway.BR;
import com.hongning.railway.R;
import com.hongning.railway.app.Constant;
import com.hongning.railway.data.AppRepository;
import com.hongning.railway.entity.reqbean.ReqAnswerSubmit;
import com.hongning.railway.entity.reqbean.ReqExam;
import com.hongning.railway.entity.resbean.BaseResExam;
import com.hongning.railway.entity.resbean.ResAnswerSubmitBean;
import com.hongning.railway.entity.resbean.ResExamCompleteBean;
import com.hongning.railway.entity.resbean.ResOptionBean;
import com.hongning.railway.ui.main.fragments.college.exam.itemviewmodel.ExamItemViewModel;
import com.hongning.railway.util.Apputils;
import com.hongning.railway.util.SpannableStringUtils;
import com.hongning.railway.util.TimeUtils;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ApiDisposableObserver;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * Author: zhangjing
 * DATA:2019-08-16 18:55
 * DESC:
 * email:zhangjingworkmol@163.com
 */
public class ExamDetailFragmentViewModel extends BaseViewModel<AppRepository> {


    public ItemBinding<ExamItemViewModel> item = ItemBinding.of(BR.viewModel, R.layout.item_answer);
    public ObservableList<ExamItemViewModel> viewlist = new ObservableArrayList<>();
    public ObservableField<String> currentpos = new ObservableField<>();
    public String time = TimeUtils.getCurrentTimeStr();
    public UISubmitButtonState uiSubmitButtonState = new UISubmitButtonState();
    public ExamDetailFragmentViewModel(@NonNull Application application, AppRepository model) {
        super(application, model);
    }
    public class UISubmitButtonState{
        SingleLiveEvent<SubmitButtonState> submitdialog = new SingleLiveEvent();
    }
    public static class SubmitButtonState{
        public String title;
        public CharSequence content;

        public SubmitButtonState(String title, CharSequence content) {
            this.title = title;
            this.content = content;
        }
    }
    public void loadExamData(String id){
        ReqExam reqExam = new ReqExam();
        reqExam.setExamId(id);
        model.getquestionslist(reqExam)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .subscribe(new ApiDisposableObserver<BaseResExam<ResOptionBean>>() {
                    @Override
                    public void onResult(BaseResExam<ResOptionBean> resOptionBeanBaseResExam) {
                        for (ResOptionBean data:resOptionBeanBaseResExam.getDataList()) {
                            viewlist.add(new ExamItemViewModel(ExamDetailFragmentViewModel.this,data));
                        }
                    }
                });
    }
    public void checkAnswer(){
        List<Integer> noanswer = new ArrayList<>();
        for (int i = 0; i <viewlist.size() ; i++) {
            if (viewlist.get(i).getResOptionBean().getSelectAnswer()!=null&&!viewlist.get(i).getResOptionBean().getSelectAnswer().isEmpty()){

            }else {
                //未作答的题目
                noanswer.add(i+1);
            }
        }
        if (noanswer.isEmpty()){
            uiSubmitButtonState.submitdialog.setValue(new SubmitButtonState("提交试卷","确认提交试题答案吗？"));
        }else {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("未完成试题：");
            stringBuffer.append(noanswer.toString().substring(1,noanswer.toString().length()-1));
            stringBuffer.append("\n" + "确认提交试题答案吗？");
            SpannableStringBuilder spannableStringBuilder = SpannableStringUtils.getBuilder("未完成试题："+noanswer.toString().substring(1,noanswer.toString().length()-1))
                    .setForegroundColor(getApplication().getResources().getColor(R.color.colorPrimary))
                    .append("\n" + "确认提交试题答案吗？")
                    .create();
            uiSubmitButtonState.submitdialog.setValue(new SubmitButtonState("提交试卷",spannableStringBuilder));
        }
    }

    public void submitAnswer(String examid,String consumetime){
        ReqAnswerSubmit reqAnswerSubmit = new ReqAnswerSubmit();
        reqAnswerSubmit.setExamId(examid);
        reqAnswerSubmit.setStaffId(Apputils.getStaffid());
        reqAnswerSubmit.setDateConsuming(consumetime);
        reqAnswerSubmit.setExamStartTime(time);
        Map<String,String> answer = new HashMap<>();
        for (ExamItemViewModel data:viewlist) {
            if (data.getResOptionBean().getSelectAnswer()!=null&&!data.getResOptionBean().getSelectAnswer().isEmpty()){
                String str = data.getResOptionBean().getSelectAnswer().toString().substring(1,data.getResOptionBean().getSelectAnswer().toString().length()-1);
                answer.put(data.getResOptionBean().getId()+"",str);
            }
        }
        reqAnswerSubmit.setResult(answer);
        model.answerSubmit(reqAnswerSubmit).compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .subscribe(new ApiDisposableObserver<ResAnswerSubmitBean>() {
                    @Override
                    public void onResult(ResAnswerSubmitBean resAnswerSubmitBean) {
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(Constant.EXTRA_DATA,resAnswerSubmitBean);
                        startContainerActivity(ExamResultFragment.class.getCanonicalName(),bundle);
                        finish();
//                        ToastUtils.showShort("你得了"+resAnswerSubmitBean.getScore()+"分");
                    }
                });
    }
}
